import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { SignInTask } from '@/types';
import { 
  getSignInTaskDetail, 
  endSignInTask, 
  manualSignIn, 
  getSignInTaskStudentDetails,
  SignInStudentDetail
} from '@/services/signIn';
import '@/styles/pages/signInDetail.scss';

const SignInDetail = () => {
  const { taskId } = useParams<{ taskId: string }>();
  const navigate = useNavigate();
  
  const [taskDetail, setTaskDetail] = useState<SignInTask | null>(null);
  const [students, setStudents] = useState<SignInStudentDetail[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [isSigningIn, setIsSigningIn] = useState(false);
  const [success, setSuccess] = useState('');
  const [isEndingTask, setIsEndingTask] = useState(false);
  const [processingStudentId, setProcessingStudentId] = useState<string | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showOnlyUnsigned, setShowOnlyUnsigned] = useState(false);
  const [stats, setStats] = useState({
    totalCount: 0,
    signedCount: 0,
    absentCount: 0,
    signInRate: 0
  });
  
  // 获取任务详情和学生签到数据
  const fetchTaskDetailAndStudents = async (taskId: number) => {
    try {
      setLoading(true);
      setError('');
      
      // 1. 获取任务详情
      const taskRes = await getSignInTaskDetail(taskId);
      console.log('任务详情响应:', taskRes);
      
      if (taskRes.code === 0 || taskRes.code === 2000) {
        const taskDetail = taskRes.data?.task || null;
        setTaskDetail(taskDetail);
        console.log('设置任务详情:', taskDetail);
        
        // 2. 获取学生签到详情
        const studentDetailsRes = await getSignInTaskStudentDetails(taskId);
        console.log('学生签到详情响应:', studentDetailsRes);
        
        if (studentDetailsRes.code === 0 || studentDetailsRes.code === 2000) {
          const { students, totalCount, signedCount, absentCount, signInRate } = studentDetailsRes.data || {};
          
          setStudents(students || []);
          setStats({
            totalCount: totalCount || 0,
            signedCount: signedCount || 0,
            absentCount: absentCount || 0,
            signInRate: signInRate || 0
          });
          
          console.log('设置学生签到数据:', students?.length || 0, '人');
        } else {
          setError(studentDetailsRes.message || '获取学生签到数据失败');
        }
      } else {
        setError(taskRes.message || '获取签到任务详情失败');
      }
    } catch (err: any) {
      console.error('获取数据出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    if (taskId) {
      fetchTaskDetailAndStudents(Number(taskId));
    }
  }, [taskId]);
  
  // 将Unix时间戳转换为格式化的日期时间字符串
  const formatTimestamp = (timestamp: number | string | null | undefined): string => {
    if (!timestamp) return '-';
    
    // 如果是字符串且包含常规格式的日期，则直接返回
    if (typeof timestamp === 'string' && timestamp.includes('-')) {
      return timestamp;
    }
    
    try {
      // 将时间戳转换为毫秒（如果是秒级时间戳）
      const ts = typeof timestamp === 'string' 
        ? parseInt(timestamp) 
        : timestamp;
        
      const milliseconds = ts > 10000000000 ? ts : ts * 1000;
      
      // 创建日期对象
      const date = new Date(milliseconds);
      
      // 使用本地时区格式化时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return String(timestamp);
    }
  };
  
  // 手动签到处理
  const handleManualSignIn = async (studentId: string) => {
    if (!taskId || !studentId.trim()) {
      setError('无效的学生学号');
      return;
    }
    
    try {
      setIsSigningIn(true);
      setError('');
      setSuccess('');
      setProcessingStudentId(studentId);
      
      const res = await manualSignIn(Number(taskId), studentId);
      
      if (res.code === 0 || res.code === 2000) {
        setSuccess(`学号 ${studentId} 手动签到成功`);
        // 刷新签到记录
        fetchTaskDetailAndStudents(Number(taskId));
        
        // 清除成功消息
        setTimeout(() => {
          setSuccess('');
        }, 3000);
      } else {
        setError(res.message || '手动签到失败');
      }
    } catch (err: any) {
      console.error('手动签到出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsSigningIn(false);
      setProcessingStudentId(null);
    }
  };
  
  // 结束签到任务
  const handleEndTask = async () => {
    if (!taskId || !taskDetail) return;
    
    // 检查任务是否已经结束
    if (taskDetail.status !== 'active') {
      setError('该签到任务已经结束');
      return;
    }
    
    if (!window.confirm('确定要结束此签到任务吗？结束后将无法继续签到。')) {
      return;
    }
    
    try {
      setIsEndingTask(true);
      setError('');
      
      const res = await endSignInTask(Number(taskId));
      
      if (res.code === 0 || res.code === 2000) {
        setSuccess('签到任务已结束');
        // 刷新任务详情
        fetchTaskDetailAndStudents(Number(taskId));
      } else {
        setError(res.message || '结束签到任务失败');
      }
    } catch (err: any) {
      console.error('结束签到任务出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsEndingTask(false);
    }
  };

  // 过滤学生列表
  const filteredStudents = students.filter(student => {
    // 搜索条件
    const matchesSearch = !searchKeyword || 
      student.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      student.student_id.toLowerCase().includes(searchKeyword.toLowerCase());
    
    // 仅显示未签到条件
    const matchesSignStatus = !showOnlyUnsigned || student.signStatus === 'absent';
    
    return matchesSearch && matchesSignStatus;
  });

  if (loading) {
    return (
      <div className="loading-container">
        <div className="spinner"></div>
        <p>正在加载签到数据...</p>
      </div>
    );
  }
  
  if (!taskDetail && !loading) {
    return (
      <div className="error-container">
        <h2>未找到签到任务</h2>
        <p>该签到任务不存在或已被删除</p>
        <button className="btn-primary" onClick={() => navigate('/sign-in')}>返回签到管理</button>
      </div>
    );
  }

  return (
    <div className="sign-in-detail-container">
      <div className="header-section">
        <div className="title-area">
          <button className="btn-back" onClick={() => navigate('/sign-in')}>
            <i className="fas fa-arrow-left"></i> 返回
          </button>
          <h1>签到详情 - {taskDetail?.course_name}</h1>
        </div>
        
        {taskDetail?.status === 'active' && (
          <button 
            className="btn-end-task" 
            onClick={handleEndTask}
            disabled={isEndingTask}
          >
            {isEndingTask ? '结束中...' : '结束签到'}
          </button>
        )}
      </div>
      
      {/* 任务信息卡片 */}
      <div className="task-info-card">
        <div className="card-header">
          <h2>签到任务 #{taskDetail?.id} {taskDetail?.description ? `- ${taskDetail.description}` : ''}</h2>
          <span className={`task-status ${taskDetail?.status}`}>
            {taskDetail?.status === 'active' ? '进行中' : '已结束'}
          </span>
        </div>
        
        <div className="info-grid">
          <div className="info-item">
            <label>课程名称:</label>
            <span>{taskDetail?.course_name || '-'}</span>
          </div>
          <div className="info-item">
            <label>班级:</label>
            <span>{taskDetail?.class_name || '-'}</span>
          </div>
          <div className="info-item">
            <label>开始时间:</label>
            <span>{formatTimestamp(taskDetail?.start_time)}</span>
          </div>
          <div className="info-item">
            <label>结束时间:</label>
            <span>{formatTimestamp(taskDetail?.end_time)}</span>
          </div>
          <div className="info-item">
            <label>签到率:</label>
            <span className="sign-rate">{stats.signInRate}%</span>
          </div>
        </div>
      </div>
      
      {/* 错误和成功消息 */}
      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}
      
      {/* 学生签到列表 */}
      <div className="students-section">
        <div className="section-header">
          <h2>学生签到状态</h2>
          
          <div className="filters">
            <div className="search-box">
              <input
                type="text"
                placeholder="搜索学生姓名或学号"
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
              />
            </div>
            
            <div className="filter-checkbox">
              <input
                type="checkbox"
                id="show-unsigned"
                checked={showOnlyUnsigned}
                onChange={(e) => setShowOnlyUnsigned(e.target.checked)}
              />
              <label htmlFor="show-unsigned">仅显示未签到</label>
            </div>
          </div>
        </div>
        
        {students.length === 0 ? (
          <div className="empty-state">
            <p>该课程暂无学生</p>
          </div>
        ) : filteredStudents.length === 0 ? (
          <div className="empty-state">
            <p>没有符合筛选条件的学生</p>
          </div>
        ) : (
          <div className="table-container">
            <table className="students-table">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>班级</th>
                  <th>签到状态</th>
                  <th>签到时间</th>
                  <th>签到方式</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredStudents.map(student => (
                  <tr key={student.id} className={student.signStatus === 'signed' ? 'signed-row' : 'absent-row'}>
                    <td>{student.student_id}</td>
                    <td>{student.name}</td>
                    <td>{student.class_name || '-'}</td>
                    <td>
                      <span className={`status-badge ${student.signStatus}`}>
                        {student.signStatus === 'signed' ? '已签到' : '未签到'}
                      </span>
                    </td>
                    <td>{formatTimestamp(student.signInTime)}</td>
                    <td>
                      {student.signInMethod === 'face' ? '人脸识别' :
                       student.signInMethod === 'manual' ? '手动签到' : '-'}
                    </td>
                    <td>
                      {taskDetail?.status === 'active' && student.signStatus === 'absent' && (
                        <button
                          className="btn-sign-in"
                          onClick={() => handleManualSignIn(student.student_id)}
                          disabled={isSigningIn && processingStudentId === student.student_id}
                        >
                          {isSigningIn && processingStudentId === student.student_id ? '签到中...' : '手动签到'}
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        
        {/* 签到统计信息 */}
        <div className="statistics-section">
          <div className="stat-item">
            <span className="label">总人数</span>
            <span className="value">{stats.totalCount}</span>
          </div>
          <div className="stat-item">
            <span className="label">已签到</span>
            <span className="value signed">{stats.signedCount}</span>
          </div>
          <div className="stat-item">
            <span className="label">未签到</span>
            <span className="value absent">{stats.absentCount}</span>
          </div>
          <div className="stat-item">
            <span className="label">签到率</span>
            <span className="value rate">{stats.signInRate}%</span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SignInDetail;
